package com.cooba.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cooba.R;
import com.cooba.activitys.MainTabActivity;
import com.cooba.bean.VersionBean;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by wuqiyan on 16/5/6.
 */
public class UpdateManager {

    private Context mContext;

    private String appId = "84d24d875e1745088dbf58d2b73406ba";
    private String version;

    //提示语
    private String updateMsg = "有最新的软件包哦！";


    private Dialog noticeDialog;
    private Dialog downloadDialog;

    private VersionBean versionBean;
    private ProgressBar mProgress_bar;
    private TextView mProgress_tv;
    private HttpUtils httpUtils;
    private HttpHandler<File> handler;


    public UpdateManager(Context context) {
        this.mContext = context;
    }

    //外部接口让主Activity调用
    public void checkUpdateInfo() {
        version = getVersion();
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("app_id", appId);
        params.addBodyParameter("version", version);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl+ServerURL.checkUpdate, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", responseInfo.result);
                try {
                    versionBean = new Gson().fromJson(responseInfo.result, VersionBean.class);
                    if (versionBean.getVersion()!=null&&!versionBean.getVersion().equals(version)){
                            showNoticeDialog();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei", msg);
            }
        });

    }

    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("软件版本更新");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (versionBean.getIs_force_update().equals("1")) {
                    ((MainTabActivity) mContext).finish();
                }
            }
        });
        noticeDialog = builder.create();
        noticeDialog.setCancelable(false);
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.show();

    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("正在下载更新包");
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress_bar = (ProgressBar) v.findViewById(R.id.progress_bar);
        mProgress_tv = (TextView) v.findViewById(R.id.progress_tv);
        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                handler.cancel();
                if (versionBean.getIs_force_update().equals("1")) {
                    ((MainTabActivity) mContext).finish();
                }
            }
        });
        downloadDialog = builder.create();
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.setCancelable(false);
        downloadDialog.show();
        downloadApk();
    }

    private void downloadApk() {
        final String apkFilePath = new StringBuilder(Environment
                .getExternalStorageDirectory().getAbsolutePath())
                .append(File.separator).append(Constants.DOWN_DIR)
                .append(File.separator).append("cooba_" + versionBean.getVersion() + ".apk")
                .toString();
        final File file = new File(apkFilePath);
        if (file.exists()) {
            file.delete();
        }
        httpUtils = new HttpUtils();
        String url = versionBean.getRes_path();
        handler = httpUtils.download(url, apkFilePath, true, false, new RequestCallBack<File>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                int progress = (int) (current * 100 / total);
                mProgress_bar.setProgress(progress);
                mProgress_tv.setText(progress + "%");
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                downloadDialog.dismiss();
                ((MainTabActivity) mContext).finish();
                CommonUtil.installAPK(mContext, file);
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
            String version = String.valueOf(info.versionName);
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
